<template>
  <div>
    <!--      表格位置-->
    <div class="button-table-box" v-loading="isLoading">
      <div class="info-in-box">
        <span class="title">产品名：</span>
        <el-input clearable @change="initPage();getProductList()" placeholder="输入产品名称" v-model="searchProduct" style="width: 15%"></el-input>
        <span class="title" style="margin-left: 30px;">分类：</span>
        <el-select v-model="category" @change="initPage();getProductList()" placeholder="请选择" style="width: 15%;">
          <el-option
            v-for="item in categoryOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
        <span class="title" style="margin-left: 30px;">状态：</span>
        <el-select v-model="status" @change="initPage();getProductList()" placeholder="请选择" style="width: 15%;">
          <el-option
            v-for="item in statusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>

        <el-button type="primary" size="mini" style="margin-left: 30px;" @click="getProductList()">查询</el-button>
      </div>
      <div class="button-box" style="margin-top: 20px;">
        <el-button type="primary"  size="small" icon="el-icon-circle-plus"
                   class="add-button" @click="dialogFormVisible = true">添加</el-button>
      </div>
      <table-list :tableAllData="tableAllData" @getTableData="getTableData" ref="tableList"></table-list>
    </div>
    <!--     添加产品弹出框-->
    <el-dialog title="添加" :visible.sync="dialogFormVisible" width="35%"  @close="cancelModal"
               v-loading="isLoading">
      <el-form>
        <el-form-item label="产品名称：" label-width="120px">
          <el-input v-model="submitForm.name" clearable placeholder="请输入产品名称" style="width: 70%;">
          </el-input>
        </el-form-item>
        <el-form-item label="产品图片:" label-width="120px">
          <div >
            <img :src="submitForm.url" class="picture" v-show="submitForm.isEdit">
            <img src="src/assets/change.png" class="change-icon" v-show="submitForm.isEdit">
            <el-upload
              action="https://hospital.osako.top/massage/picture/upload"
              list-type="picture-card"
              :file-list="fileList"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              :on-change="handlePhoto"
              :class="{hide:hideUpload}"
              v-loading.fullscreen.lock="fullscreenLoading">
              <i class="el-icon-plus"></i>
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item label="分类：" label-width="120px">
          <el-select v-model="submitForm.categoryId" placeholder="请选择" style="width: 70%;">
            <el-option
              v-if="item.label !== '全部'"
              v-for="item in categoryOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="价格：" label-width="120px">
          <el-input v-model="submitForm.price" type="number" clearable placeholder="请输入价格" style="width: 70%;">
          </el-input>
        </el-form-item>
        <el-form-item label="详情：" label-width="120px">
          <el-input v-model="submitForm.description" type="text" maxlength="19" clearable placeholder="产品详情(最多19个字哦)" style="width: 70%;">
          </el-input>
        </el-form-item>
          <el-form-item label="上架时间：" label-width="120px">
            <!-- 日期选择框-->
            <el-date-picker
              v-model="dateValue"
              type="daterange"
              style="width: 70%;"
              unlink-panels
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :picker-options="pickerOptions">
            </el-date-picker>
        </el-form-item>
        <el-form-item label="状态：" label-width="120px">
          <el-select v-model="status" placeholder="请选择状态" style="width: 70%;">
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelModal">取 消</el-button>
        <el-button type="primary" @click="uploadPicture">确 定</el-button>
      </div>
    </el-dialog>
    <!--     修改出诊计划弹出框-->
    <el-dialog title="修改" :visible.sync="updateDialog" width="50%"  @close="cancelModal"
               v-loading="isLoading">
      <el-form>
        <el-form-item label="产品名称：" label-width="120px">
          <el-input v-model="updateForm.name" clearable placeholder="请输入产品名称" style="width: 70%;">
          </el-input>
        </el-form-item>
        <el-form-item label="产品图片:" label-width="120px">
          <div style="display: flex;">
            <img :src="updateForm.url" class="picture" v-show="updateForm.isEdit">
            <img src="https://img.osako.top/img/FuDMaKMofWgfDwT9yozLP5-C83B2" class="change-icon" v-show="updateForm.isEdit">
            <el-upload
              action="https://hospital.osako.top/massage/picture/upload"
              list-type="picture-card"
              :file-list="fileList"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              :on-change="handlePhoto"
              :class="{hide:hideUpload}"
              v-loading.fullscreen.lock="fullscreenLoading">
              <i class="el-icon-plus"></i>
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item label="分类：" label-width="120px">
          <el-select v-model="updateForm.categoryId"  placeholder="请选择" style="width: 70%;">
            <el-option
              v-if="item.label !== '全部'"
              v-for="item in categoryOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="价格：" label-width="120px">
          <el-input v-model="updateForm.price" type="number" clearable placeholder="请输入价格" style="width: 70%;">
          </el-input>
        </el-form-item>
        <el-form-item label="详情：" label-width="120px">
          <el-input v-model="updateForm.description" maxlength="19" clearable placeholder="产品详情(最多19个字哦)" style="width: 70%;">
          </el-input>
        </el-form-item>
        <el-form-item label="上架时间：" label-width="120px">
          <!-- 日期选择框-->
          <el-date-picker
            v-model="updateValue"
            type="daterange"
            style="width: 70%;"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="状态：" label-width="120px">
          <el-select v-model="updateForm.up" placeholder="请选择状态" style="width: 70%;">
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelModal">取 消</el-button>
        <el-button type="primary" @click="uploadPicture()">确 定</el-button>
      </div>
    </el-dialog>
    <page-pagination :page-list="pageList" ref="pagePagination"></page-pagination>
    <!--    用作删除的弹框-->
    <delete-dialog :dialog="deleteDialog" ref="deleteDialog"></delete-dialog>
  </div>
</template>

<script>
import {tips} from "@/common/js/optionTips";
import {addProduct, deleteProduct, getAllProduct, queryProductCategory, upAndDown, updateProduct} from "@/api/product";
import {dateFormYMD, formatDate} from "@/common/js/dateFormYMD";
import {getToken} from "@/utils/auth";
import axios from "axios";

export default {
  name: "addProduct",
  data() {
    return {
      //分类
      category:'全部',
      categoryOptions: [],
      //上架时间选择框
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            end.setTime(end.getTime() + 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            end.setTime(end.getTime() + 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            end.setTime(end.getTime() + 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      imgUrl:'',
      dialogVisible: false,
      fileList: [],
      hideUpload: false,
      fullscreenLoading: false, // 进行整个屏幕的加载的
      // 添加产品的日期
      dateValue: '',
      // 更新产品信息
      updateValue: '',
      // 产品
      submitForm: {
        buycount:99,
        description: "",
        end: "",
        name: "",
        price: "",
        start: "",
        up: "",
        url: "",
        categoryId: '',
        isEdit:false
      },
      // 保存编辑产品的信息
      updateForm: {
        id:'',
        buycount:99,
        description: "",
        end: "",
        name: "",
        price: "",
        start: "",
        up: "",
        url: "",
        categoryId: '',
        isEdit:false
      },
      // 添加模态框的
      dialogFormVisible: false,
      // 修改模态框的
      updateDialog: false,
      selectDoctorID: '',
      // 顶部筛选信息
      isLoading: false,
      searchProduct: '',
      status: '上架',
      statusOptions: [
        {
          value: '上架',
          label: '上架'
        }, {
          value: '下架',
          label: '下架'
        }],
      // 表格数据
      tableAllData: {
        dataNull: false,
        tableTitle: [{
          prop: 'ID',
          label: '产品ID',
          width: '100',
          option: ''
        }, {
          prop: 'name',
          label: '产品名',
          width: '100',
          option: ''
        }, {
          prop: 'price',
          label: '价格',
          width: '80',
          option: ''
        },
          {
            prop: 'start',
            label: '开始时间',
            width: '100',
            option: ''
          },
          {
            prop: 'end',
            label: '结束时间',
            width: '100',
            option: ''
          },
          {
            prop: 'description',
            label: '描述',
            width: '250',
            option: ''
          },
          {
            prop: 'Status',
            label: '状态',
            width: '80',
            option: ''
          }],
        tableData: [],
        option: {
          width: '150',
          button: []
        }
      },
      // 底部分页的数据
      pageList: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      // 删除的模态框的数据
      deleteDialog: {
        title: '产品',
        dialogFormVisible: false,
        id: ''
      },
      deleteScope: {}, // 用作当从组件传过来确认删除时用的
    }
  },
  methods: {
    initPage:function (){
      this.pageList.pageNum = 1;
      this.pageList.pageSize = 10;
    },
    // 当上传了一张照片上去
    handlePhoto: function (file, fileList) {
      this.imgFile = file;
      this.hideUpload = true;
      console.log('this,imgFile',this.imgFile)
      console.log('this.hideUpload',this.hideUpload)
    },
    // 删除上传的照片
    handleRemove(file, fileList) {
      if (fileList.length === 0) {
        this.fileList = []
      } else {
        let dl = this.fileList.indexOf(file);
        this.fileList.splice(dl, 1)
      }
      this.hideUpload = fileList.length >= 1
    },
    handlePictureCardPreview(file) {
      this.imgUrl = file.url;
      this.dialogVisible = true;
    },
    updateProduct:function (){
      this.updateForm.up = this.updateForm.up === '上架' ? 0 : 1;
      this.updateForm.start = dateFormYMD(this.updateValue[0]);
      this.updateForm.end = dateFormYMD(this.updateValue[1]);
      console.log("修改产品",this.updateForm)
      if(this.updateForm.url === '' || this.updateForm.description === '' || this.updateForm.name === '' || this.updateForm.price === '' ||  this.updateForm.up === ''|| this.updateForm.categoryId === ''){
        tips('error','请将产品信息填写完整');
        this.fullscreenLoading = false;
        return;
      }
      updateProduct(this.updateForm.id,this.updateForm).then(res => {
        this.fullscreenLoading = false;
        if(res.code === 200){
          tips('success','修改成功')
        }
        this.getProductList();
        this.cancelModal();
      }).catch(() =>{
        tips('error','该产品名已存在')
      })
    },
    //上传图片
    uploadPicture: function() {
      //编辑产品但是没上传图片
      if(this.updateForm.isEdit && !this.hideUpload){
        this.updateProduct()
        return;
      }//未上传图片
      if(!this.hideUpload){
        tips('error','请上传产品图片')
        return;
      }
      console.log(this.submitForm)
      if(!this.updateForm.isEdit&&(this.submitForm.description === '' || this.submitForm.name === '' || this.submitForm.price === '' || this.dateValue === '' || this.submitForm.categoryId === '')){
        tips('error','请将产品信息填写完整');
        this.fullscreenLoading = false;
        return;
      }
      this.fullscreenLoading = true;
      const url = 'https://hospital.osako.top/massage/picture/upload';
      const config = {
        headers: {
          'Content-Type': 'multipart/form-data',
          'Authorization': getToken()
        }
      };
      const param = new FormData();
      // 将图片加入formdata
      param.append('file', this.imgFile.raw);
      axios.post(url, param, config).then(res => {
        if (res.data.code === 200) {
          if(this.updateForm.isEdit){
            this.updateForm.url = res.data.data
            this.updateProduct()
          }else{
            console.log("添加产品")
            this.submitForm.url = res.data.data
            this.submitForm.start = dateFormYMD(this.dateValue[0]);
            this.submitForm.end = dateFormYMD(this.dateValue[1]);
            this.submitForm.up = this.status === '上架' ? 0 : 1;
            addProduct(this.submitForm).then(res=>{
              if(res.code === 200){
                this.fullscreenLoading = false;
                this.$notify({
                  title: '成功',
                  message: '添加成功',
                  type: 'success'
                });
                this.getProductList();
                this.cancelModal();
              }else if(res.code === 404){
                tips('error',res.message);
              }
            }).catch(()=>{
              this.fullscreenLoading = false;
              tips('error','产品名已存在')
            })
          }
        }
      }).catch(() => {
        this.fullscreenLoading = false;
        tips('error','添加失败')
      });
    },
    // 关闭模态框
    cancelModal: function () {
      //取消隐藏上传框
      this.hideUpload = false;
      //隐藏添加产品框
      this.dialogFormVisible = false;
      //隐藏删除框
      this.deleteDialog.dialogFormVisible = false;
      //隐藏更新茶农框
      this.updateDialog = false;
      this.selectDoctorID = '';
      this.submitForm.description = '';
      this.submitForm.name = '';
      this.submitForm.up = '';
      this.submitForm.price = '';
      this.submitForm.url = '';
      this.submitForm.categoryId = '';
      this.submitForm.categoryName = '';
      this.updateForm.isEdit = false;
     // console.log('dateValue',this.dateValue)
      this.dateValue = '';
      this.fileList = [];
      this.updateForm.isEditCategory = false;
      //this.updateForm = {};
      this.imgFile = ''
    },

    // 获取表格的点击按钮的信息反馈
    getTableData: function (option) {
      if (option.buttonName === '编辑') {
        this.updateForm.id = option.scopeRow.ID;
        this.updateForm.name = option.scopeRow.name;
        this.updateForm.price = option.scopeRow.price;
        this.updateForm.start = option.scopeRow.start;
        this.updateForm.end = option.scopeRow.end;
        this.updateForm.description = option.scopeRow.description;
        this.updateForm.up = option.scopeRow.Status;
        this.updateForm.categoryId = option.scopeRow.categoryId;
        this.updateForm.categoryName = option.scopeRow.categoryName;
        this.updateValue = formatDate(option.scopeRow.start,option.scopeRow.end);
        this.updateForm.url = option.scopeRow.url;
        this.updateForm.isEdit = true;
        this.updateDialog = true;
        console.log('updateForm',this.updateForm)
      } else if (option.buttonName === '删除') {
        this.deleteScope = option; // 将删除的数据存起来
        this.deleteDialog.dialogFormVisible = true; // 打开删除弹窗
        this.deleteDialog.isProduct = true;
        this.deleteDialog.id = option.scopeRow.name; // 发送删除id
      }else if (option.buttonName === '上架') {
        this.$confirm('确认上架吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        }).then(() => {
          upAndDown(option.scopeRow.ID,0)
          setTimeout(()=>{
            this.getProductList()
          },50)
          tips('success','上架成功')
        })
      }else if (option.buttonName === '下架') {
        this.$confirm('确认下架吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        }).then(() => {
          upAndDown(option.scopeRow.ID,1)
          setTimeout(()=>{
            this.getProductList()
          },50)
          tips('success','下架成功')
        })
      }
    },
    // 用户点击删除某条产品信息
    deleteProduct: function () {
      deleteProduct(this.deleteScope.scopeRow.ID).then(res => {
        if (res.code === 200) {
          this.deleteDialog.dialogFormVisible = false;
          this.$refs.tableList.deleteData(this.deleteScope.scopeIndex)
        }
      }).catch(() => {
        this.deleteDialog.dialogFormVisible = false;
        tips('error', '删除失败')
      });
    },
    // 获取分类
    getCategoryList:function (){
      let that = this
      queryProductCategory(1,50,'').then(res => {
        this.categoryOptions = [];
        if(res.code === 200){
          that.categoryOptions.push({
            value:'全部',
            label:'全部',
            id:0
          })
          res.data.records.forEach(function (item){
            that.categoryOptions.push({
              value:item.id,
              label:item.name,
            })
          })
        }
        //that.category = that.categoryOptions[0].value
      })
    },
    // 从数据库获取师傅信息列表
    getProductList: function () {
      this.tableAllData.tableData = [];
      let _this = this;
      getAllProduct(
        this.category === '全部' ? '' : this.category,
        '',
        this.pageList.pageNum,
        this.pageList.pageSize,
        this.status === '上架' ? '0' : '1',
        this.searchProduct
      ).then(res => {
        if (res.code === 200 ){
          this.pageList = {
            pageNum: res.data.current,
            pageSize: res.data.size,
            total: res.data.total
          };
          this.tableAllData.option.button = []
          this.tableAllData.option.button.push({
              size: 'mini',
              type: 'primary',
              name:  this.status === '上架' ? '下架' : '上架'
            }, {
              size: 'mini',
              type: 'success',
              name: '编辑'
            }, {
              size: 'mini',
              type: 'danger',
              name: '删除'
            }
          )
          if (res.data.records.length === 0){
            this.tableAllData.dataNull = true;
            return;
          }
          res.data.records.forEach(function (item) {
            if(_this.status === (item.up === "0" ? '上架' : '下架')){
              _this.tableAllData.tableData.push({
                ID: item.id,
                name: item.name,
                price: item.price,
                description: item.description,
                start: item.start,
                end: item.end,
                Status: _this.status,
                url: item.url,
                categoryId:item.categoryId,
                categoryName:item.categoryName
              })
            }
          })
          this.tableAllData.dataNull = false;
        } else {
          this.tableAllData.dataNull = true
        }
      })
    },
    // 子组件分页通过调用父组件的方法进行调用更新表格
    fatherMethod: function (pageNum, pageSize) {
      this.pageList.pageNum = pageNum;
      this.pageList.pageSize = pageSize;
      this.getProductList()
    }
  },
  mounted() {
    this.getCategoryList();
    this.getProductList();
  }
}
</script>

<style lang="scss">
@import "src/common/scss/common";

.hide .el-upload-picture-card{

  display:none;

}

.picture {
  width: 146px;
  height: 146px;
  margin-left: 20%;
}
.change-icon{
  @include icon-style(80px, 80px);
  margin: 4%;
}
.button-table-box{
  @include width-margin(90%, 100%);
  margin-top: 15px;
}
</style>
